package database

import (
	"fmt"
	"github.com/gofiber/fiber/v2/log"
	"github.com/kadycui/fiber-ci/config"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

// MySQLInit Connect creates a connection to database
func MySQLInit() {
	DBHost := config.App.DBHost
	DBPort := config.App.DBPort
	DBUser := config.App.DBUser
	DBPassword := config.App.DBPassword
	DBName := config.App.DBName
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		DBUser,
		DBPassword,
		DBHost,
		DBPort,
		DBName,
	)
	// logger.Info("MySQL连接信息:", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	sqlDB, err := db.DB()

	if err != nil {
		log.Fatalf("failed to obtain database DB: %v", err)
	}

	// 设置连接池参数
	sqlDB.SetConnMaxLifetime(time.Minute * 5) // 设置连接可复用的最大时间
	sqlDB.SetMaxIdleConns(10)                 // 连接池中连接的最大数量
	sqlDB.SetMaxOpenConns(100)                // 打开数据库连接的最大数量

	// 测试连接是否正常
	err = sqlDB.Ping()
	if err != nil {
		log.Fatalf("failed to ping DB: %v", err)
	}

	log.Info("MySQL连接成功!")
	DB = db

}
